package com.jacen.fzxs.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jacen.fzxs.service.IWallService;
import com.jacen.fzxs.service.impl.WeiXinService;
import com.jacen.fzxs.util.SignUtil;

/**
 * 微信接口 （预留）
 * 
 * @author Jacen
 * 
 */
@Controller
public class WeiXinController extends BaseController {

	@Resource
	private IWallService wallService;

	private static Logger logger = LoggerFactory.getLogger(WeiXinController.class);

	@RequestMapping(value = "/weixin.do", method = RequestMethod.GET)
	public void init(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戮
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");
		System.out.println("signature:" + signature + "\n" + "nonce:" + nonce + "\n" + "echostr:" + echostr);
		PrintWriter out = response.getWriter();
		// 通过检验 signature 对请求进行校验，若校验成功则原样返回 echostr，表示接入成功，否则接入失败
		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
			out.print(echostr);
		}
		out.close();
		out = null;
	}

	@RequestMapping(value = "/weixin.do", method = RequestMethod.POST)
	public void getWall(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		byte[] buf = new byte[1024];
		StringBuffer sb = new StringBuffer();
		while ((req.getInputStream().read(buf)) != -1) {
			sb.append(new String(buf));
			buf = new byte[1024];// 重新生成，避免和上次读取的数据重复
		}
		String xml = sb.toString().trim();
		System.out.println("xml========\n" + xml);
		parseXml(xml, resp);
	}

	private void parseXml(String string, HttpServletResponse response) {
		String MsgType = "";
		try {
			Document doc = DocumentHelper.parseText(string);
			Element root = doc.getRootElement();
			MsgType = root.element("MsgType").getText();
			WeiXinService wxService = new WeiXinService();
			wxService.setMsgType(MsgType);
			wxService.setResponse(response);
			wxService.setRoot(root);
			wxService.service(wallService);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}

}
